import { defineEventHandler, readBody } from 'h3'
import redis from '../../util/redis'
import { checkAdminKey } from './_utils'
import { recordLog } from '../../util/log'

// POST /api/admin/ym.delete with JSON { key }
export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  try {
    const body = await readBody(event) as any
    const key = body?.key
    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }

    try {
      const del = await (redis as any).del(`ym:${key}`)
      await recordLog(event as any, { message: `admin/ym: deleted key=${key} result=${del}`, userId: 0 })
      return { status: 'ok', key, deleted: del }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `admin/ym: redis del failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis del failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `admin/ym: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
